package com.codinghero.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public final class ListUtils {
	
	public static <T> boolean isEmpty(List<T> list) {
		if (list == null || list.size() == 0)
			return true;
		else
			return false;
	}
	
	public static <T> boolean contains(List<T> father, T e) {
		if (e == null)
			return false;
		for (T f : father) {
			if (f == null)
				continue;
			if (f.equals(e))
				return true;
		}
		return false;
	}
	
	public static <T> boolean containsOne(List<T> father, List<T> son) {
		if (son == null || son.size() == 0)
			return false;
		for (T f : father) {
			if (f == null)
				continue;
			for (T s : son) {
				if (f.equals(s))
					return true;
			}
		}
		return false;
	}
	
	public static <T> boolean containsTwo(List<T> father, List<T> son) {
		if (son == null || son.size() == 0)
			return false;
		int match = 0;
		for (T f : father) {
			if (f == null)
				continue;
			for (T s : son) {
				if (f.equals(s))
					match++;
			}
		}
		return match == 2;
	}

	public static <T> List<T> removeDuplicate(List<T> list) {
		List<T> resultList = new ArrayList<T>();
		Iterator<T> iterator = list.iterator();
		while (iterator.hasNext()) {
			T t = iterator.next();
			if (!resultList.contains(t))
				resultList.add(t);
			list.remove(iterator);
		}
		return resultList;
	}
	
	public static <T extends HasKey> Map<String, T> toMap(List<T> list) {
		Map<String, T> map = new HashMap<String, T>();
		for (T t : list) {
			map.put(t.getKey(), t);
		}
		return map;
	}
	
	public static <K extends Object, V extends HasKey> List<V> toList(Map<K, V> map) {
		List<V> list = new ArrayList<V>();
		for (Entry<K, V> e : map.entrySet()) {
			list.add(e.getValue());
		}
		return list;
	}

	public static <T extends HasKey> List<T> removeEmptyItem(List<T> list, Class<T> clazz) {
		if (list == null)
			return null;
		T emptyItem = BeanUtils.newInstance(clazz);
		Iterator<T> iter = list.iterator();
		while (iter.hasNext()) {
			T t = iter.next();
			if (emptyItem != null && t != null)
				// both key null
				if (emptyItem.getKey() == null && t.getKey() == null)
					iter.remove();
				// key not null & equal
				else if (emptyItem.getKey() != null && t.getKey() != null 
						&& emptyItem.getKey().equals(t.getKey()))
					iter.remove();
		}
		return list;
	}
}
